package tps12.axwax.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Encapsulates access to the login servlet.
 * 
 * @author Travis
 *
 */
public class LoginClientImpl implements LoginClient {

	private static String SERVLET_NAME = "login/";
	
	public final String baseUrl;
	
	public LoginClientImpl() {
		baseUrl = GWT.getModuleBaseURL() + SERVLET_NAME;
	}
	
	public static class LoginResults {
		public boolean loggedIn;
		public boolean admin;
		public String url;
		public String name;
	}

	/* (non-Javadoc)
	 * @see tps12.axwax.client.LoginClient#login(java.lang.String, com.google.gwt.user.client.rpc.AsyncCallback)
	 */
	public void login(String url, final AsyncCallback<LoginResults> callback) {
		String query = "?url=" + URL.encodeComponent(url);
		RequestBuilder req = new RequestBuilder(RequestBuilder.GET, baseUrl + query);
		req.setHeader("Accept", "application/json");
		
		req.setCallback(new RequestCallback() {
			@Override public void onError(Request request, Throwable exception) {
				callback.onFailure(exception);
			}

			@Override public void onResponseReceived(Request request, Response response) {
				JSONObject o = JSONParser.parse(response.getText()).isObject();
				if (o == null)
					callback.onFailure(new Throwable("Response text did not contain JSON object"));
				else {
					LoginResults res = new LoginResults();
					res.loggedIn = o.get("loggedin").isBoolean().booleanValue();
					res.admin = o.get("admin").isBoolean().booleanValue();
					res.url = o.get("url").isString().stringValue();
					res.name = o.get("name").isString().stringValue();
					callback.onSuccess(res);
				}
			}
		});
		try {
			req.send();
		} catch (RequestException e) {
			callback.onFailure(e);
		}
	}
}
